package com.system.Tools;

import org.apache.poi.util.IOUtils;
import org.apache.poi.util.StringUtil;
import sun.misc.BASE64Decoder;

import java.io.*;

public class ImgTool {

    public static String saveImg(String Url) {
        String[] url = Url.split("base64,");
        String u = url[1];
        // Base64解码
        OutputStream out = null;
        try {
            byte[] b = new BASE64Decoder().decodeBuffer(u);
            String ImagePath = "/";
            ImagePath = ImagePath.replaceAll("\\\\", "/");
            String paths = ImagePath + "image" + System.currentTimeMillis() + ".png";
            // 生成图片
            out = new FileOutputStream(new File(paths));
            out.write(b);
            out.flush();
            out.close();
            return paths;
        } catch (IOException e1) {
            return "";
        }finally {
            if(null != out){
                try {
                    out.close();
                }catch (Exception e){}
            }
        }
    }

    /**
     * 将图片保存为bate数组
     *
     * @param imageUrl
     * @return
     */
    public static byte[] returnImgToBate(String imageUrl) {
        if (null == imageUrl || "".equals(imageUrl)) {
            return null;
        }
        byte[] byteImage = null;
        InputStream is = null;
        try {
            is = new FileInputStream(imageUrl);
            // 将输入流转化为数组
            byteImage = IOUtils.toByteArray(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return byteImage;
    }
}
